package com.example.fill.output;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

/**
 * .xls 文件输出
 */
public class XlsType extends OutputType<WritableWorkbook,WritableSheet>{


    @Override
    public WritableWorkbook createPlatform(File file) {
        try {
            return Workbook.createWorkbook(new FileOutputStream(file));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public WritableSheet getPlatformCapacity(WritableWorkbook platform, String pageName, int index) {
        return platform.createSheet(pageName,index);
    }

    @Override
    public void beforeWrite(WritableWorkbook platform, WritableSheet platformCapacity) {
        //nothing
    }

    @Override
    public void initTitle(WritableSheet platform, List<String> rowData) {
        for (int i = 0; i < rowData.size(); i++) {
            try {
                platform.addCell(new Label(i, 0, rowData.get(i)));
            } catch (WriteException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void initBody(WritableSheet platform, int yIndex, List<String> rowData) {
        for (int i = 0; i < rowData.size(); i++) {
            try {
                platform.addCell(new Label(i, yIndex + 1, rowData.get(i)));
            } catch (WriteException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void onPostExecute(Integer integer) {
        if (!file.exists()) return;
        final Uri uri;
        uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri,context.getContentResolver().getType(uri));
        context.startActivity(Intent.createChooser(intent, file.getName()));
    }

    @Override
    public void releasePlatform(WritableWorkbook platform) {
        try {
            platform.write();
            platform.close();
        } catch (IOException | WriteException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void notifyWriteFinished() {

    }


    @Override
    public String getType() {
        return ".xls";
    }



}
